package com.sf.fy.uav.applet.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sf.fy.uav.applet.service.LoginService;
import com.sf.fy.uav.common.enums.ServicePrefixEnum;
import com.sf.fy.uav.common.utils.RedisPrefixKey;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author LTQ
 */
@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {

    @Value("${wx.rescueAppid:wxa9995496636a5ee1}")
    private String rescueAppid;

    @Value("${wx.rescueSecret:ed609905dc5a817ea3d7091a5ea90654}")
    private String rescueSecret;

    @Value("${proxy-url:sfproxy.intsit.sfcloud.local}")
    private String proxyUrl;

    @Value("${is-use-proxy:false}")
    private boolean isUseProxy;

    private final RedisTemplate redisTemplate;


    @Override
    public String getRescueStableToken() {
        String accessToken = (String) redisTemplate.opsForValue().get(ServicePrefixEnum.RESCUE + RedisPrefixKey.APPLET_STABLE_TOKEN);
        if (ObjectUtils.isEmpty(accessToken)) {
            Map params = new HashMap();
            params.put("grant_type", "client_credential");
            params.put("force_refresh", false);
            params.put("appid", rescueAppid);
            params.put("secret", rescueSecret);
            String body = com.sf.fy.uav.task.utils.HttpClientUtil.sendPostJsonRepeatProxy("https://api.weixin.qq.com/cgi-bin/stable_token", JSONObject.toJSONString(params), proxyUrl, 80, isUseProxy);
            JSONObject object = JSON.parseObject(body);
            accessToken = object.getString("access_token");
            /*access_token有效时长*/
            int expires_in = object.getInteger("expires_in");
            /*过期时间减去10毫秒：10毫秒是网络连接的程序运行所占用的时间*/
            redisTemplate.opsForValue().set(ServicePrefixEnum.RESCUE + RedisPrefixKey.APPLET_STABLE_TOKEN, accessToken);
            redisTemplate.expire(ServicePrefixEnum.RESCUE + RedisPrefixKey.APPLET_STABLE_TOKEN, expires_in - 5, TimeUnit.SECONDS);
        }
        return accessToken;
    }
}
